/*
 * Copyright 2014 Graham Smith
 */
package uk.co.wobblycogs.vegas.riff;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 *
 * @author Graham Smith
 */
public class RIFFResource extends RIFFChunk {

	private final int HEADER_START_POSITION = 24;
	private final int TYPE_OFFSET = 28;
	private final int RESOURCE_LENGTH_OFFSET = 60;
	//private final int RESOURCE_OFFSET = 120;

	private ResourceType resourceType;
	private int headerLength;
	private int resourceLength;
	private String resource;

	public RIFFResource() {
	}

	public ResourceType getResourceType() {
		return resourceType;
	}

	/**
	 * The number of bytes that make up the resource string. For files this will
	 * be a path for generated media it is a (GUID) key.
	 *
	 * @return
	 */
	public int getResourceLength() {
		return resourceLength;
	}

	public String getResource() {
		return resource;
	}

	@Override
	public void load(ByteBuffer byteBuffer) {
		super.load(byteBuffer);

		//Extract various bits of known data from the binary blob.
		ByteBuffer bb = ByteBuffer.wrap(getData());
		bb = bb.order(ByteOrder.LITTLE_ENDIAN);

		bb.rewind();
		bb.position(HEADER_START_POSITION);
		bb.mark();
		headerLength = bb.getInt();

		RIFFUtilities.move(bb, TYPE_OFFSET);
		resourceType = ResourceType.getResourceType(bb.getInt());
		resourceLength = bb.getInt();

		bb.reset();
		RIFFUtilities.move(bb, headerLength);
		resource = RIFFUtilities.getString(bb, resourceLength);
	}

	@Override
	public String toString() {
		return getType() + " (" + RIFFUtilities.bytesToHex(getRawType()) + ")    Size: " + getLength() + "    Type: " + getResourceType() + "    Resource: " + getResource();
	}

}
